<template>
  <div class="hello">
    <div>
      <h1>{{ msg }}</h1>
    <button @click="loadIframe">加载子页面</button>
    </div>
    <iframe ref="childIfrRef" class="c-ifr" :src="ifrUrl"></iframe>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data: () =>{
    return {
      ifrUrl: null,
    }
  },
  methods: {
    //点击按钮加载iframe
    loadIframe() {
      this.ifrUrl = "http://localhost:8082/";//子页面地址
      //注册事件，等待子页面回复
      window.addEventListener("message", this.messageHandler);
    },
   
    //处理子页面回复消息
    messageHandler(event) {
       /* eslint-disable */ 
      console.log("收到消息:", event)
      if(event.source != this.$refs.childIfrRef.contentWindow) {//抛弃来自其他页面回复消息
          return ;
      }
      let data = event.data;
      let url = window.location.href;
      if(data.type == 1) {//收到子页面准备就绪通知，发起插入html片段请求
        let msg = {
          type: 5,
          msg: `<div>
              <button onclick="eval(
                (()=>{
                console.log('在子页面中触发点击事件');
                console.log('${url}');
                window.parent.postMessage({
                  type: 2,
                  msg: '收到子页面按钮点击事件！'
                }, '${url}');
              })()
              )">通知父页面</button>
            </div>`
        }
    
        //回复消息给子页面   参数event.origin指的是谁发的再发给谁
        this.$refs.childIfrRef.contentWindow.postMessage(msg, event.origin)
      }else if(data.type == 2) {//收到子页面点击按钮的请求
        console.log("子页面点击按钮后父页面响应：", data.msg)
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.c-ifr {
  width: 500px;
  height: 400px;
  border: 2px solid steelblue;
}
</style>
